package com.sqx.modules.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.health.common.ApiConsts;
import com.sqx.modules.health.config.RemoteConfig;
import com.sqx.modules.health.entity.Record;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.mapper.RecordMapper;
import com.sqx.modules.health.service.IRecordService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.DateUtil;
import com.sqx.modules.health.utils.Remote;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gxy
 * @since 2022-07-14
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IRecordService recordService;

    @Override
    public Record getOneByDevSn(String devSN, Integer type) {
        return recordMapper.getOneByDevSn(devSN, type);
    }

    @Override
    public Record getLastTest(Long uid) {
        return recordMapper.getLastTest(uid);
    }

    @Override
    public Record getRecord(Long id, String today, Integer type) {
        return recordMapper.getRecord(id, today, type);
    }

    @Override
    public Record getLastRecord(String imei) {
        return recordMapper.getLastRecord(imei);
    }

    @Value("${orgid.dataid.admin-orgid}")
    private String adminOrgid;


    /**
     * 发送患者动态血压关系
     * @param jsonObject
     * @return
     */
    @Override
    public String sendPat(JSONObject jsonObject) {

        String dpreStr = ApiConsts.DataTypeEnum.BLPRESSURE.getDPre();
        String imei_a = jsonObject.getString("imei");
        boolean status = dpreStr.contains(imei_a);
        if(status){

            System.out.println("包含");
            SysUserEntity user = userService.getRedisByUid(jsonObject.getLong("uid")); // 首先获取用户表所有信息
            //patid 为用户表id+6位随机数。
            int randomNum = (int) ((Math.random() * 9 + 1) * 100000); // 随机数 6 位
            //String patId= ruser.getId()+"".concat("_").concat(""+randomNum);
            String patId = "8k870107-e37b-4330-b201-" + Remote.autoGenericCode((user.getUserId().toString()), 6).concat("" + randomNum);
            String patIdPortName = patId + ".pdf";
            String createTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");

            //写入record表
            Record rrecord = new Record();
            rrecord.setUid(jsonObject.getLong("uid"));
            rrecord.setDoctorid(jsonObject.getLong("doctorid"));
            rrecord.setType(jsonObject.getInteger("type"));
            rrecord.setPatid(patId);
            rrecord.setFile("/static/reports/"+patIdPortName); // File.separator
//            rrecord.setFile(RemoteConfig.urlReportFile +patIdPortName); // File.separator
            rrecord.setFlag(0);//血压 B1-测量中;B2-测量结束;
            rrecord.setImei(jsonObject.getString("imei"));
            rrecord.setRecordtime(createTime);
            recordService.save(rrecord);
            return "爱奥乐动态血压成功";

        }else {
            //获取数据
            SysUserEntity user = userService.getRedisByUid(jsonObject.getLong("uid")); // 首先获取用户表所有信息
            //patid 为用户表id+6位随机数。
            int randomNum = (int) ((Math.random() * 9 + 1) * 100000); // 随机数 6 位
            //String patId= ruser.getId()+"".concat("_").concat(""+randomNum);
            String patId = "8k870107-e37b-4330-b201-" + Remote.autoGenericCode((user.getUserId().toString()), 6).concat("" + randomNum);
//        String patId= user.getId()+"".concat("_").concat(""+randomNum);
            String patIdPortName = patId + ".pdf";

            Calendar beforeTime = Calendar.getInstance();
            beforeTime.add(Calendar.MINUTE,-5);
            Date beforeD = beforeTime.getTime();
            String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);
            String pdTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);
//            String createTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");
//            String pdTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");

            JSONObject jsonBody = new JSONObject();
//        jsonBody.put("orgid","32c43dd8-5994-4bff-84be-395653fc8e09");
//            jsonBody.put("orgid", "e987ccfd-4f40-4128-9aed-7e9cde9706f1");
            jsonBody.put("orgid", adminOrgid);
            //jsonBody.put("patientId","8k870107-e37b-4330-b201-4d796cebee03");
            jsonBody.put("patientId", patId);
            jsonBody.put("patientName", user.getNickName());
            if (ObjectUtil.isNotEmpty(user.getCardid())) {
                jsonBody.put("birthday", getBirthday(user.getCardid()));
            }
            jsonBody.put("sex", ObjectUtil.equals(user.getGender(), 1) ? "男" : "女");
            jsonBody.put("CreateDate", createTime);
            jsonBody.put("pdTime", pdTime);
            jsonBody.put("dataType", "动态血压");
            jsonBody.put("analysisType", "0");
            //userDevice.getDeviceid(); 根据患者id获取绑定设备的编码
            jsonBody.put("deviceMac", jsonObject.getString("imei"));

            //写入record表
            Record rrecord = new Record();
            rrecord.setUid(jsonObject.getLong("uid"));
            rrecord.setDoctorid(jsonObject.getLong("doctorid"));
            rrecord.setType(jsonObject.getInteger("type"));
            rrecord.setPatid(patId);
//            rrecord.setFile(RemoteConfig.urlReportFile+ patIdPortName); // File.separator
            rrecord.setFile("/static/reports/"+patIdPortName); // File.separator
            rrecord.setFlag(0);//血压 B1-测量中;B2-测量结束;
            rrecord.setImei(jsonObject.getString("imei"));
            rrecord.setRecordtime(createTime);
            recordService.save(rrecord);
            JSONObject patAPI = Remote.sendPatAPI(RemoteConfig.patReportUrl, new JSONObject(), jsonBody);
            return patAPI.getString("message");

        }
    }

    public String getBirthday(String cardNo){
        String birthday = "";
        if (cardNo.length() == 15) {
            birthday = "19" + cardNo.substring(6, 8) + "-"
                    + cardNo.substring(8, 10) + "-"
                    + cardNo.substring(10, 12);
        } else if (cardNo.length() == 18) {
            birthday = cardNo.substring(6, 10) + "-"
                    + cardNo.substring(10, 12) + "-"
                    + cardNo.substring(12, 14);
        }
        return birthday;
    }

    /**
     * 报告下载并写入本地服务器
     * 结束检测
     * @param rrecord
     * @return
     */
    @Override
    public String downLoadReoprt(Record rrecord) throws MalformedURLException {
        //String patIdFileName=rrecord.getId()+".pdf";
//        String patIdFileName=rrecord.getPatid()+".pdf"; //表中字段加完后，就可以替换

        URL url = new URL(rrecord.getFile());
        String patIdFileName = FilenameUtils.getName(url.getPath());

//        //获取数据
//        User user = userService.getById(ruser.getId()); // 首先获取用户表所有信息
        try {
            //rrecord.getFile() 表中字段加完后，就可以替换
            Remote.downLoadReoprtByUrl(rrecord.getFile(), patIdFileName, RemoteConfig.reportLcoalPath);
            rrecord.setFlag(1);
            recordService.saveOrUpdate(rrecord);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RemoteConfig.reportLcoalPath + "/" + patIdFileName;
    }

}
